import os
#import installer


class Version(object):
	'''A single application version.
	
	@property MSI state to indicate that installer is .msi file.
	@property EXE state to indicate that installer windows executable file.'''

	#Installer types:
	MSI = 0
	EXE = 1

	def __init__(self, name, version, path):
		'''__init__()
		
		@param name name of the application.
		@param version version idenifier.
		@param path path to version folder.
		'''

		self.name = name
		self.version = version
		self.ver_path = path
		self.getInstaller()

	def getInstaller(self):
		'''get installer object

		Installer is selected in this order if found:
		1) .msi file
		2) setup.exe file
		3) read from installer.version file
		'''

		files = os.listdir(self.ver_path)
		#TODO: will trigger on first .msi found, should decide if that is wanted
		for installer in files:
			if os.path.splitext(installer)[-1].lower() == '.msi':
				self.installer = installer
				self.inst_type = self.MSI
				self.getParams()
				return
		self.params = ''
		if 'setup.exe'.upper() in [f.upper() for f in files]:
			self.installer = 'setup.exe'
			self.inst_type = self.EXE
		else:
			installer_file = os.path.join(self.ver_path, '..', 'installer.' + self.version)
			fsock = open(installer_file)
			self.installer = fsock.readline()
			fsock.close()
			self.inst_type = getattr(self,os.path.splitext(self.installer)[-1][1:].upper())
			
	def getParams(self, param_file=None):
		'''Get installation parameters
		
		@param param_file paramerters file, if not provided, uses parameters.version
		'''
		
		if not param_file:
			param_file = 'parameters.'+self.version
		f_path = os.path.join(self.ver_path, '..', param_file)
		if os.path.exists(f_path):
			fsock = open(f_path)
			self.params = fsock.readline()
			fsock.close()
		else:
			self.params = ''

	def __cmp__(self, other):
		'''Compare versions'''
		#TODO: better version compare logic. example: 1.0 > 1.0-beta but currently 1.0-beta > 1.0

		if self.version > other.version:
			return 1
		elif self.version < other.version:
			return -1
		return 0

